
package com.hnrd.crud.controller;
import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hnrd.crud.mapper.TUserMapper;
import com.hnrd.crud.pojo.TUser;
import com.hnrd.crud.shiro.ActiveSession;
import com.hnrd.crud.shiro.MyRealm;
import com.hnrd.crud.shiro.MyShiroManager;
import com.hnrd.crud.utils.JWTTokenUtil;

@RequestMapping("login")
@RestController
public class UserLoginController {
	@Autowired
	private MyRealm myRealm;
	@Autowired
	private TUserMapper tUserMapper;
	
	/**
	 * 用户注册
	 * @param user
	 * @return
	 */
	@RequestMapping("userRegister")
	public ResponseEntity<Map<String,Object>> register(@RequestBody TUser user){
		Map<String,Object> map=new HashMap<>();
		map.put("msg","注册成功！");
		Md5Hash md5Hash = new Md5Hash(user.getPassword(),"lhm",5);
		user.setPassword(md5Hash.toString());
		try {
			tUserMapper.insert(user);
			return new ResponseEntity<>(map,HttpStatus.OK);
		} catch (Exception e) {
			map.put("msg","注册失败！");
			return new ResponseEntity<>(map,HttpStatus.BAD_GATEWAY);
		}
	}
	
	/**
	 * 用户登陆
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("userlogin")
	public ResponseEntity<Map<String, Object>> login(@RequestParam("username")String username,@RequestParam("password")String password){
		Map<String, Object> map=new HashMap<>();
		map.put("msg","登陆成功！");
		String token = JWTTokenUtil.createToken(username, password);
		UsernamePasswordToken shiro_token=new UsernamePasswordToken(username, password,true);
		Subject subject=MyShiroManager.setMyRealm(myRealm);
		try {
			subject.login(shiro_token);
			subject.getSession().setAttribute(token, subject);
			SessionKey sessionKey =new DefaultSessionKey(subject.getSession().getId());
			ActiveSession.map.put(username,sessionKey);
			map.put("token", token);
			return new ResponseEntity<Map<String,Object>>(map,HttpStatus.OK);
		} catch (Exception e) {
			map.put("msg","登陆失败! 账户或密码不正确 ");
			return new ResponseEntity<>(map,HttpStatus.BAD_GATEWAY);
		}
	}
	
}
